package servlet;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import oracle.net.aso.b;
import pojo.Book;
import pojo.Customer;
import pojo.Favourite;
import pojo.Order;
import pojo.User;
import service.BookManager;
import service.OrderManager;
import service.factory.ManagerFactory;
import verify.MyVerify;


@WebServlet("/order")
public class OrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private OrderManager manager;
	private BookManager bookManager;
       
    public OrderServlet() {
        super();
        manager = ManagerFactory.getOrderManagerInstance();
        bookManager = ManagerFactory.getBookManagerInstance();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String bid = request.getParameter("bid");
		if (bid==null) {
			request.setAttribute("info", "no book select");
			request.getRequestDispatcher("list").forward(request, response);
			return;
		}
		HttpSession session = request.getSession();
		Map<Book,Integer> cart = (Map<Book, Integer>) session.getAttribute("cart");
		if (cart==null) {
//			request.setAttribute("info", "you have no books to buy");
			cart = new HashMap<Book,Integer>();
		}
		Book book = bookManager.getBook(bid);
		if (book!=null) {
			if (cart.containsKey(book)) {
				cart.put(book, cart.get(book)+1);
			}else{
				cart.put(book, 1);
			}
			request.setAttribute("cart", cart);
			session.setAttribute("cart", cart);
			request.getRequestDispatcher("order.jsp").forward(request, response);
		}else{
			request.getRequestDispatcher("list").forward(request, response);
		}
		
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		Map<Book,Integer> cart = (Map<Book, Integer>) session.getAttribute("cart");
		if (cart==null) {
//			request.setAttribute("info", "you have no books to buy");
			cart = new HashMap<Book,Integer>();
		}
		request.setAttribute("info", "buy success");
		request.getRequestDispatcher("order.jsp").forward(request, response);
	}

}
